﻿using Cxuu.Common;
using Cxuu.Models;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using System.Threading.Tasks;

namespace Cxuu.Repository
{
    [UseDI(ServiceLifetime.Scoped)]
    public class LogRepository : BaseRepository<LogSql, PetaPocoContext>
    {

        public LogRepository(PetaPocoContext petaPocoContext) : base(petaPocoContext) { }


        public async Task<Page<ViewLogSql>> GetSqlListAsync(int page, int limit, int uid, string orderBy, string keyword = "")
        {
            Sql sql = Sql.Builder;
            sql.Select("A.Id,B.Username,B.Nickname,A.UserId,A.ControllerAction,A.Ip,A.Time,A.DoThing")
                .From("cxuu_log_sql as A")
                .LeftJoin("cxuu_admin_user as B")
                .On("A.UserId = B.Id");

            if (uid != 0)
                sql.Where("A.UserId = @0", uid);

            if (!string.IsNullOrEmpty(keyword))
                sql.Where("Time like @0", "%" + keyword + "%");

            if (!string.IsNullOrEmpty(orderBy))
                sql.OrderBy(orderBy);



            return await CreateDAO().PageAsync<ViewLogSql>(page, limit, sql);
        }
        public async Task AutoDelAsync(int num)
        {
            int conNum = await CreateDAO().ExecuteScalarAsync<int>("select COUNT(Id) from cxuu_log_sql");
            if (conNum > num)
                await CreateDAO().ExecuteAsync("delete from cxuu_log_sql order by id asc limit 1");
        }

    }
}
